#pragma once
#include <istream>
#include <iostream>
#include <unordered_map>
#include <string>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace std;
using namespace LogModule;

const string defpath = "./dictionary.txt";
const string sep = ":";

class Dict
{
public:
    Dict(const string &path = defpath)
        : _dict_path(path)
    {
    }

    bool LoadDict()
    {
        ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "打开字典：" << _dict_path << " 失败";
            return false;
        }
        LOG(LogLevel::INFO) << "打开字典：" << _dict_path << " 成功";
        string line;
        while (getline(in, line))
        {
            auto pos = line.find(sep);
            if (pos == string::npos)
            {
                LOG(LogLevel::WARNING) << "字典格式错误";
                continue;
            }
            auto english = line.substr(0, pos);
            auto chinese = line.substr(pos + sep.size());
            if (chinese.empty() || english.empty())
            {
                LOG(LogLevel::WARNING) << "字典识别错误:" << line;
                continue;
            }
            _dict.insert(make_pair(english, chinese));
            LOG(LogLevel::INFO) << "加载" << line;
        }
        in.close();
        return true;
    }

    string translate(const string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入翻译[" << client.Ip() << "," << client.Port() << "]#" << word << "->None";
            return "unknown";
        }
        LOG(LogLevel::INFO) << "进入翻译[" << client.Ip() << "," << client.Port() << "]#" << word << "->" << iter->second;
        return iter->first + "->" + iter->second;
    }

    ~Dict()
    {
    }

private:
    string _dict_path;
    unordered_map<string, string> _dict;
};